<?php


namespace App\Http\Controllers\App;

use App\Enums\BlindBoxEnum;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Repositories\BlindBox\BlindBoxRepository;
use App\Repositories\BlindBox\DrawRecordRepository;
use App\Repositories\BlindBox\ExchangeRepository;
use App\Repositories\BlindBox\PoolPrizeRepository;
use App\Repositories\BlindBox\PoolRepository;
use App\Repositories\BlindBox\PoolTemplateRepository;
use App\Repositories\BlindBox\SettingRepository;
use App\Repositories\BlindBox\UserRepository;
use App\Resource\BlindBox\User\Resource as UserResource;
use App\Resource\BlindBox\Setting\Resource as SettingResource;
use App\Response\Response;
use App\Services\Tools\RedisService;
use Illuminate\Http\Request;

class BlindBoxController extends BaseController
{

    public function draw(Request $request)
    {
        $userId = (int)UID;
        $params = $request->only('send_gif_id', 'accept_user_list', 'type', 'room_id', 'count');

        $v = app('validator')->make(
            $request->all(),
            [
                'send_gif_id'      => "required|numeric",
                'accept_user_list' => "required",
                'type'             => "required",
                'room_id'          => "required|numeric",
                'count'            => "required|numeric",
            ],
            [
                'required' => ' :attribute必须输入',
                'numeric'  => ' :attribute必须为数字'
            ],
            [
                'send_gif_id'      => '送礼ID',
                'accept_user_list' => '收礼人列表',
                'type'             => '送礼类型',
                'room_id'          => '房间ID',
                'count'            => '送礼数量',
            ]
        );

        if ($v->fails()) {
            throw new BasicException(10010, getValidateMessage($v->messages()));
        }

        $draw = BlindBoxRepository::getInstance()->draw($userId, $params['send_gif_id'], $params['accept_user_list'],
            $params['type'], (int)$params['room_id'], (int)$params['count']);

        $draw['is_first_apply'] = 0;
        $draw['time']           = (int)(microtime(true) * 1000);

        return Response::sendData($draw, '盲盒礼物赠送成功');
    }

    public function setting(Request $request)
    {
        $setting = SettingRepository::getInstance()->setting(false);
        $model   = SettingResource::make($setting);
        return Response::sendData($model);
    }

    public function info(Request $request)
    {
        $userId  = (int)UID;
        $balance = UserRepository::getInstance()->infoWithBalance($userId);
        $setting = SettingRepository::getInstance()->setting();
        $balance->max_score = $setting->score_value;
        return UserResource::make($balance);
    }

    public function getExchangeGiftList(Request $request)
    {
        $userId                 = (int)UID;
        $type                   = $request->input('type', 'default');
        $poolExchangeList       = PoolRepository::getInstance()->getExchangeGiftList(['type' => $type]);
//        $userExchangeRecordList = ExchangeRepository::getInstance()->getUserList($userId, ['id', 'pool_id']);
//        if (!empty($userExchangeRecordList)) {
//            $userExchangeRecordListWithPoolId = $userExchangeRecordList->KeyBy('pool_id');
//        }
//        foreach ($poolExchangeList as &$poolExchange) {
//            $poolExchange->exchanged = false;
//            if (isset($userExchangeRecordListWithPoolId[$poolExchange['pool_id']])) {
//                $poolExchange->exchanged = true;
//            }
//        }

        //按照金银铜排序
        $giftTypeList     = array_flip(BlindBoxEnum::GIFT_TYPE_LIST);
        $poolExchangeList = $poolExchangeList->sort(function ($val1, $val2) use ($giftTypeList) {
            if ($giftTypeList[$val1->gift_type] > $giftTypeList[$val2->gift_type]) {
                return true;
            }
        });

        return Response::sendData(array_values($poolExchangeList->toArray()));
    }

    public function getUserBlindBoxGiftList(Request $request)
    {
        $userId         = (int)UID;
        $type           = $request->input('type', 'default');
        $poolList       = PoolRepository::getInstance()->list(['type' => $type], ['id', 'gift_type']);
        $poolListWithId = $poolList->KeyBy('id');
        $poolIds        = $poolListWithId->keys()->toArray();
        $poolGiftList   = PoolPrizeRepository::getInstance()->getPoolGiftListByIds($poolIds);
        $prizePoolIds = $poolGiftList->pluck('pool_id')->unique()->toArray();
        $emptyPoolIds = array_diff($poolIds, $prizePoolIds);

        //如果有礼物表为空则查询模板
        if(!empty($emptyPoolIds)){
            $templateGiftList = PoolTemplateRepository::getInstance()->getGiftListByPoolIds($emptyPoolIds);
            $poolGiftList = $poolGiftList->merge($templateGiftList);
        }

        //查询用户开出的盲盒记录
        //$userDrawRecordList     = DrawRecordRepository::getInstance()->getUserUnduplicatedPrizeRecord(['user_id' => $userId]);
        $userPoolDrawRecordList = [];
        foreach ($poolIds as $poolId) {
            $userPoolIllustrate = app('redis')->hgetall(ExchangeRepository::userIllustrateCacheKey . "_" . $userId . "_" . $poolId);

            $userPoolDrawRecordList[$poolId] = $userPoolIllustrate;
        }
        //标记礼物是否被抽中
        $poolGiftListRes = [];
        $giftCount       = [];
        $userDrawCount   = [];
        $tempPoolId      = 0;
        foreach ($poolGiftList as $poolGift) {
            if ($poolGift->pool_id != $tempPoolId && !empty($tempPoolId)) {
                $poolGiftListRes[$tempPoolId]['percent'] = intval(($userDrawCount[$tempPoolId] ?? 0) / $giftCount[$tempPoolId] * 100);
            }
            $tempPoolId   = $poolGift->pool_id;
            $tempPoolGift = $poolGift->toArray();
            if (empty($giftCount[$tempPoolId])) {
                $giftCount[$tempPoolId] = 1;
            } else {
                $giftCount[$tempPoolId]++;
            }

            if (isset($userPoolDrawRecordList[$poolGift->pool_id]) && isset($userPoolDrawRecordList[$poolGift->pool_id][$poolGift->id])
                && $userPoolDrawRecordList[$poolGift->pool_id][$poolGift->id] == 1) {
                if (empty($userDrawCount[$tempPoolId])) {
                    $userDrawCount[$tempPoolId] = 1;
                } else {
                    $userDrawCount[$tempPoolId]++;
                }

                $tempPoolGift['is_open'] = 1;
            } else {
                $tempPoolGift['is_open'] = 0;
            }

            $poolGiftListRes[$tempPoolId]['gift_list'][] = $tempPoolGift;
        }

        if (!empty($poolGiftListRes)) {
            $poolGiftListRes[$tempPoolId]['percent'] = intval(($userDrawCount[$tempPoolId] ?? 0) / $giftCount[$tempPoolId] * 100);
        }

        $giftTypeList = array_flip(BlindBoxEnum::GIFT_TYPE_LIST);
        uksort($poolGiftListRes, function ($val1, $val2) use ($giftTypeList, $poolListWithId) {
            if ($giftTypeList[$poolListWithId[$val1]['gift_type']] > $giftTypeList[$poolListWithId[$val2]['gift_type']]) {
                return true;
            }
        });

        return Response::sendData(array_values($poolGiftListRes));
    }

    /**
     * @param Request $request
     * @return string
     */
    public function getUserDrawRecordList(Request $request)
    {
        //todo根据池子类型进行分页查询
        $userId       = (int)UID;
        $type         = $request->input('type', 'default');
        $poolTypeList = BlindBoxEnum::GIFT_TYPE_LIST;
        $pool         = $request->input('pool', 'bronze');
        if (!in_array($pool, $poolTypeList)) {
            throw new BasicException(-1, '参数异常');
        }

        $poolInfo = PoolRepository::getInstance()->one(['type' => $type, 'gift_type' => $pool]);
        if (empty($poolInfo)) {
            throw new BasicException(-1, '奖池不存在');
        }
        $poolId = $poolInfo['id'];

        $page                 = $request->input('page', 1);
        $perPage              = $request->input('per_page', 100);
        $userRecordList       = DrawRecordRepository::getInstance()->getUserRecord(['user_id' => $userId, 'pool_id' => $poolId], $page, $perPage);
        $acceptUserIds        = array_unique($userRecordList->pluck('accept_user_id')->toArray());
        $acceptUserIds[]      = $userId;
        $userInfoList         = RedisService::batchGetUserBaseInfo($acceptUserIds, true);
        $userInfoListWithId   = array_column($userInfoList, null, 'user_id');
        $userRecordListResult = [];
        foreach ($userRecordList as $record) {
            $record->accept_user_nickname = $userInfoListWithId[$record->accept_user_id] ? $userInfoListWithId[$record->accept_user_id]['nickname'] : '';
            $record->nickname             = $userInfoListWithId[$record->user_id] ? $userInfoListWithId[$record->user_id]['nickname'] : '';
            $record->create_time          = $record->created_at->toDateTimeString();
            $userRecordListResult[]       = $record->toArray();
        }

        return Response::sendData($userRecordListResult);
    }

    /**
     * @param Request $request
     * @return string
     */
    public function exchangePrize(Request $request)
    {
        $userId       = (int)UID;
        $type         = $request->input('type', 'default');
        $poolTypeList = BlindBoxEnum::GIFT_TYPE_LIST;
        $pool         = $request->input('pool', 'bronze');
        if (!in_array($pool, $poolTypeList)) {
            throw new BasicException(-1, '参数异常');
        }

        $poolInfo = PoolRepository::getInstance()->one(['type' => $type, 'gift_type' => $pool]);
        if (empty($poolInfo)) {
            throw new BasicException(-1, '奖池不存在');
        }
        $poolId = $poolInfo['id'];
        ExchangeRepository::getInstance()->exchangePrize($userId, $poolId);

        return Response::sendData([], '兑换成功');
    }

    public function getBoxGiftList(Request $request)
    {
        $data = PoolRepository::getInstance()->getBoxGiftList($request->input());
        return Response::sendData($data);

    }
}
